//
//  AddTimeViewController.m
//  FitTime
//
//  Created by Zone on 16/3/31.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import "AddTimeViewController.h"
#import "WeekCollectionViewCell.h"
#import "MusicViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@interface AddTimeViewController ()<UIPickerViewDelegate, UIPickerViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, DCPathButtonDelegate, MusicNameSearch>

@property (nonatomic, strong) UIPickerView *picker;
@property (nonatomic, strong) NSMutableArray *hours;
@property (nonatomic, strong) NSMutableArray *minutes;
@property (nonatomic, strong) NSMutableArray *weeks; //选定星期数组
@property (nonatomic, strong) NSArray *weeksArray; //星期数组
@property (nonatomic, assign) NSInteger hour; //选定小时
@property (nonatomic, assign) NSInteger minute; //选定分钟
@property (nonatomic, strong) DCPathButton *dcPathButton; //闹钟类型按钮
@property (nonatomic, strong) UILabel *colckType;//闹钟类型
@property (nonatomic, strong) NSArray *colckTypeArr;
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) UIButton *musicButton; //铃声选择
@property (nonatomic, strong) NSString *music; //铃声选择
@property (nonatomic, strong) NSString *musicName; //铃声名字

@end

@implementation AddTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.musicName = @"Airship";
    
    _hour = 7;
    _minute = 30;
    
    // 获取本地推送数组
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *localArray = [app scheduledLocalNotifications];
    NSLog(@"❤️%@", localArray);
    // 删除所有本地推送
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    // CoreData路径
//    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    self.colckTypeArr = @[@"上班", @"起床", @"约会", @"运动", @"提醒"];
    self.weeksArray = @[@"周一 ", @"周二 ", @"周三 ", @"周四 ", @"周五 ", @"周六 ", @"周日 "];
    self.weeks = [NSMutableArray arrayWithCapacity:0];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    backImageView.userInteractionEnabled = YES;
    [self.view addSubview:backImageView];
    
    backImageView.image = [UIImage imageNamed:@"闹钟壁纸.png"];
    backImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    self.dcPathButton = [[DCPathButton alloc]
                         initDCPathButtonWithSubButtons:5
                         totalRadius:70
                         centerRadius:20
                         subRadius:20
                         centerImage:@"custom_center"
                         centerBackground:nil
                         subImages:^(DCPathButton *dc){
                             [dc subButtonImage:@"custom_1" withTag:0];
                             [dc subButtonImage:@"custom_2" withTag:1];
                             [dc subButtonImage:@"custom_3" withTag:2];
                             [dc subButtonImage:@"custom_4" withTag:3];
                             [dc subButtonImage:@"custom_center" withTag:4];
                         }
                         subImageBackground:nil
                         inLocationX:SCREENWIDTH / 2 locationY:SCREENHEIGHT / 2 + 60
                         toParentView:backImageView];
    
    _dcPathButton.delegate = self;
    
    [self creatColckType];
    
    self.hours = [NSMutableArray arrayWithCapacity:0];
    self.minutes = [NSMutableArray arrayWithCapacity:0];
    
    for (int i = 0; i < 24; i ++) {
        [_hours addObject:[NSString stringWithFormat:@"%d",i]];
    }
    for (int i = 0; i < 60; i ++) {
        [_minutes addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    self.picker = [UIPickerView new];
    [self.view addSubview:_picker];
    
    [_picker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(SCREENWIDTH, 150 * SCALEHEIGHT));
        make.top.equalTo(@150);
    }];
    
    _picker.delegate = self;
    _picker.dataSource = self;
    _picker.showsSelectionIndicator = YES;
    [_picker selectRow:7 + 50 * 24 inComponent:0 animated:NO];
    [_picker selectRow:30 + 50 * 60 inComponent:1 animated:NO];

    // 添加按钮
    UIButton *addTime = [UIButton buttonWithTitle:@"确定" frame:CGRectZero target:self action:@selector(addAction:)];
    [self.view addSubview:addTime];
    
    [addTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(SCREENWIDTH / 4);
        make.size.mas_equalTo(CGSizeMake(SCREENWIDTH / 3 * SCALEWIDTH, 40 * SCALEHEIGHT));
        make.bottom.equalTo(@-100);
    }];
    
    [addTime.layer setCornerRadius:40 * SCALEHEIGHT / 2];
    addTime.layer.masksToBounds = YES;
    addTime.titleLabel.font = [UIFont italicSystemFontOfSize:20];
    [addTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addTime.backgroundColor = [UIColor colorWithRed:0.000 green:0.502 blue:1.000 alpha:1.000];
    addTime.layer.borderWidth = 2;
    addTime.layer.borderColor = [[UIColor whiteColor] CGColor];
    // 取消按钮
    UIButton *returnTime = [UIButton buttonWithTitle:@"取消" frame:CGRectZero target:self action:@selector(returnAction:)];
    [self.view addSubview:returnTime];
    
    [returnTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(-SCREENWIDTH / 4);
        make.size.mas_equalTo(addTime);
        make.bottom.equalTo(@-100);
    }];
    
    [returnTime.layer setCornerRadius:40 * SCALEHEIGHT / 2];
    returnTime.layer.masksToBounds = YES;
    returnTime.titleLabel.font = [UIFont italicSystemFontOfSize:20];
    [returnTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    returnTime.backgroundColor = [UIColor colorWithRed:0.000 green:0.502 blue:1.000 alpha:1.000];
    returnTime.layer.borderWidth = 2;
    returnTime.layer.borderColor = [[UIColor whiteColor] CGColor];
    
    // 星期选择CollectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.itemSize = CGSizeMake(SCREENWIDTH / 7 - 10, SCREENWIDTH / 7 - 10);
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView *collectionView = [[UICollectionView alloc ] initWithFrame:CGRectMake(0, 100 * SCALEHEIGHT, SCREENWIDTH, SCREENWIDTH / 7) collectionViewLayout:layout];
    
    // 允许多选
    collectionView.allowsMultipleSelection = YES;
    
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    
    // cell的重用池
    [collectionView registerClass:[WeekCollectionViewCell class] forCellWithReuseIdentifier:@"WeekCollectionViewCell"];
    
    UILabel *headLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:headLabel];
    headLabel.text = [NSString stringWithFormat:@"Today:%@", _todayWeek];
    headLabel.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:25];
    headLabel.textColor = [UIColor colorWithWhite:0.502 alpha:1.000];
    
    [headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(collectionView.mas_top);
        make.width.offset(SCREENWIDTH);
        make.height.offset(50 * SCALEHEIGHT);
    }];
    
    self.musicButton = [UIButton buttonWithTitle:[NSString stringWithFormat:@"铃声: %@ 🌟", _musicName] frame:CGRectZero target:self action:@selector(musicAction:)];
    [backImageView addSubview:_musicButton];
    
    _musicButton.titleLabel.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:20];;
    
    [_musicButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREENWIDTH, 50 * SCALEHEIGHT));
        make.bottom.mas_equalTo(backImageView.mas_bottom).offset(-20);
    }];
    
    UIButton *more = [UIButton buttonWithTitle:@"更多.png" frame:CGRectZero target:self action:@selector(musicAction:)];
    
    [self.musicButton addSubview:more];
    
    [more mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(30 * SCALEHEIGHT);
        make.right.equalTo(_musicButton);
        make.width.offset(50 * SCALEWIDTH);
        make.centerY.equalTo(_musicButton.mas_centerY);
    }];
}

#pragma mark 铃声选择
- (void)musicAction:(id)sender {

    MusicViewController *musicVC = [[MusicViewController alloc] init];
    
    [self.navigationController pushViewController:musicVC animated:YES];
    
    musicVC.delegate = self;
}

- (void)musicNumber:(NSInteger)musicNumber {
    
    if (musicNumber != 100) {
        
        _musicName = self.musicArr[musicNumber];
        
        [_musicButton setTitle:[NSString stringWithFormat:@"铃声: %@ 🌟", _musicName] forState:UIControlStateNormal];
    }
    
}

- (void)button_0_action{
    [_dcPathButton centerImage:@"custom_1"];
    [_dcPathButton returnCenter];
    self.colckType.text = _colckTypeArr[0];
}

- (void)button_1_action{
    [_dcPathButton centerImage:@"custom_2"];
    [_dcPathButton returnCenter];
    self.colckType.text = _colckTypeArr[1];
}

- (void)button_2_action{
    [_dcPathButton centerImage:@"custom_3"];
    [_dcPathButton returnCenter];
    self.colckType.text = _colckTypeArr[2];
}

- (void)button_3_action{
    [_dcPathButton centerImage:@"custom_4"];
    [_dcPathButton returnCenter];
    self.colckType.text = _colckTypeArr[3];
}

- (void)button_4_action{
    [_dcPathButton centerImage:@"custom_center"];
    [_dcPathButton returnCenter];
    self.colckType.text = _colckTypeArr[4];
}

- (void)creatColckType {
    
    if (!_dcPathButton.isExpanded) {

        if (!self.colckType) {
            
            self.colckType = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
            [self.view addSubview:self.colckType];
            self.colckType.text = @"提醒";
            self.colckType.textColor = [UIColor colorWithRed:1.000 green:0.502 blue:0.000 alpha:1.000];
            self.colckType.font = [UIFont systemFontOfSize:20 weight:1.5];
            
            [self.colckType mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.view);
                make.centerY.equalTo(self.view).offset(100);
                make.size.mas_equalTo(CGSizeMake(200, 50));
           }];
            
        } else {
            self.colckType.hidden = YES;
        }
    } else {
        
        self.colckType.hidden = NO;
    }
}

#pragma mark UIPickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
        return 24 * SCALEHEIGHT * 100;
    else
        return 60 * SCALEHEIGHT * 100;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 60 * SCALEHEIGHT;
}

#pragma mark UIPickerViewDelegate Methods
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    if (!view){
        view = [[UIView alloc]init];
    }
    
    [[pickerView.subviews objectAtIndex:1] setHidden:TRUE];
    [[pickerView.subviews objectAtIndex:2] setHidden:TRUE];
    
    
    if (component == 0) {
        
        UILabel *hoursLabel = [UILabel labelWithFrame:CGRectMake(SCREENWIDTH / 16, 0, SCREENWIDTH * 3 / 8, 50 * SCALEHEIGHT) color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
        
        hoursLabel.text = [NSString stringWithFormat:@"%@时", [_hours objectAtIndex:row % _hours.count]];
        
        hoursLabel.font = [UIFont fontWithName:@"Digital-7" size:30];
        
        [view addSubview:hoursLabel];
        
        return view;
    }
    else {
        
        UILabel *minutesLabel = [UILabel labelWithFrame:CGRectMake(SCREENWIDTH / 16, 0, SCREENWIDTH * 3 / 8, 50 * SCALEHEIGHT) color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
        
        minutesLabel.text = [NSString stringWithFormat:@"%@分", [_minutes objectAtIndex:row % _minutes.count]];
        minutesLabel.font = [UIFont fontWithName:@"Digital-7" size:30];
        
        [view addSubview:minutesLabel];
        
        return view;
    }
    
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    if (component == 0) {
        _hour = [[_hours objectAtIndex:row % _hours.count] intValue];
    }
    if (component == 1) {
        _minute = [[_minutes objectAtIndex:row % _minutes.count] intValue];
    }
}

#pragma mark AddAction
- (void)addAction:(id)sender {
    
    //添加Action
    if (_weeks.count != 0) {
        
        NSMutableString *weekStr = [NSMutableString string];
        
        for (NSString *str in _weeks) {
            [weekStr appendString:str];
        }
        
        NSString *timeID = [NSString stringWithFormat:@"%ld-%ld-%@", _hour, _minute, weekStr];
        //判断是否已经存在此闹钟
        int isOK = 0;
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"TImes" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"%@", error);
        }else{
            
            for (TImes *tim in fetchedObjects) {
                if ([tim.timeID isEqualToString:timeID]) {
                    isOK = 1;
                }
            }
        }
        //不存在
        if (isOK == 0) {
            
            TImes *timer = [NSEntityDescription insertNewObjectForEntityForName:@"TImes" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            
            timer.type = self.colckType.text;
            
            timer.hour = [NSNumber numberWithInteger: _hour];
            
            timer.minute = [NSNumber numberWithInteger: _minute];
            
            timer.week = weekStr;
            
            timer.timeID = timeID;
            
            timer.musicName = _musicName;
            
            [_coreDataManager saveContext];
            
#pragma mark 发送本地通知
            
            if (_weeks.count == 7) {
                
                UILocalNotification *notification = [[UILocalNotification alloc] init];
                

                if (notification) {
                    
                    notification.fireDate = [NSDate dateWithTimeIntervalSince1970:(_hour - 8)*60*60 + _minute * 60];//本次开启立即执行的周期
                    notification.repeatInterval = kCFCalendarUnitDay;//每天都响
                    
                    notification.soundName = [NSString stringWithFormat:@"%@.mp3", self.musicName];
                    
                    // 提示信息
                    NSString *Time = [NSString stringWithFormat:@"❤️时间到了❤️"];
                    notification.alertBody = Time;
                    NSString *Type = [NSString stringWithFormat:@"亲😊～闹钟响了"];
                    notification.alertAction = NSLocalizedString(Type, nil);
                    
                    //取消推送用的字典
                    NSDictionary * inforDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld-%ld-%@-%@", _hour, _minute, weekStr, _musicName] forKey:[NSString stringWithFormat:@"%ld-%ld-%@", _hour, _minute, weekStr]];
                    notification.userInfo =inforDic;
                    
                    // 添加到系统
                    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
                    
                }
                
            } else {
                for (NSString *weekString in _weeks) {
                    
                    UILocalNotification *notification = [[UILocalNotification alloc] init];
                    
                    if (notification) {
                        
                        int week;
                        
                        if ([weekString isEqualToString:@"周四 "]) {
                            week = 0;
                        } else if ([weekString isEqualToString:@"周五 "]) {
                            week = 1;
                        } else if ([weekString isEqualToString:@"周六 "]) {
                            week = 2;
                        } else if ([weekString isEqualToString:@"周日 "]) {
                            week = 3;
                        } else if ([weekString isEqualToString:@"周一 "]) {
                            week = 4;
                        } else if ([weekString isEqualToString:@"周二 "]) {
                            week = 5;
                        } else {
                            week = 6;
                        }
                        
                        int day = 24 * 60 * 60 * week;
                        
                        notification.fireDate = [NSDate dateWithTimeIntervalSince1970:(_hour - 8)*60*60 + _minute * 60 + day];//本次开启立即执行的周期
                        notification.repeatInterval = kCFCalendarUnitWeek;//每周都响

                        notification.soundName = [NSString stringWithFormat:@"%@.mp3", self.musicName];
;
                        // 提示信息
                        NSString *Time = [NSString stringWithFormat:@"❤️时间到了❤️"];
                        notification.alertBody = Time;
                        NSString *Type = [NSString stringWithFormat:@"亲😊～闹钟响了"];
                        notification.alertAction = NSLocalizedString(Type, nil);
                        
//                        NSLog(@"%ld%ld", _hour, _minute);
                        
                        //取消推送用的字典
                        NSDictionary * inforDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld-%ld-%@-%@-%@", _hour, _minute, weekStr, weekString, _musicName] forKey:[NSString stringWithFormat:@"%@-%@", weekStr, weekString]];
                        notification.userInfo =inforDic;
                        
                        // 添加到系统
                        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
                        
                    }
                    
                }
                
            }

        }
        //闹钟已经存在
        else {
            UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"此闹钟已经存在" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alartView show];
            
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
        self.navigationController.navigationBarHidden = NO;
        
        self.navigationController.tabBarController.tabBar.hidden = NO;
        

    } else {
        
        NSString *string = @"确定";
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"还没有选择星期呦～😊" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertC addAction:ok];
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
      
    }
    
}
#pragma mark returnAction
- (void)returnAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationController.tabBarController.tabBar.hidden = NO;
    
}

#pragma mark item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 7;
}

#pragma mark 创建cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WeekCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WeekCollectionViewCell" forIndexPath:indexPath];
    
    cell.row = indexPath.row;
    
    return cell;
}

#pragma mark cell的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 点击特效
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath] cache:YES];
   
    [UIView commitAnimations];
    
    // 根据indexPath获取cell
    WeekCollectionViewCell *cell = (WeekCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    cell.weekImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"iconfont-星期%ld-2", indexPath.row + 1]];
    
    [self.weeks addObject:self.weeksArray[indexPath.row]];
    
}

#pragma mark 取消点击的方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath] cache:YES];
    
    [UIView commitAnimations];
    
    WeekCollectionViewCell *cell = (WeekCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.weekImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"iconfont-星期%ld", indexPath.row + 1]];
    
    [self.weeks removeObject:self.weeksArray[indexPath.row]];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
